package com.example.spider.common.starter;

import cn.hutool.core.bean.BeanException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Map;

/**
 * 爬虫任务启动器管理器
 * 启动后是否触发一次启动所有爬虫任务
 *
 * @author lym
 */
@Slf4j
public class SpiderStarterTrigger implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            Map<String, SpiderStarter> spiderStarterMap = event.getApplicationContext().getBeansOfType(SpiderStarter.class);
            log.info("starting all spiderStarters...(total:{})", spiderStarterMap.size());
            spiderStarterMap.forEach((spiderStarterName, spiderStarter) -> {
                spiderStarter.startSpiders();
            });
            log.info("started all spiderStarters");
        }catch (BeanException e){
            log.error("can't find any SpiderStarter", e);
        }
    }
}
